/**
 * 
 */
package com.lehecai.core.api;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Sunshow
 *
 */
public class ApiResponseBatchUpdateParser {

    protected static final transient Logger logger = LoggerFactory.getLogger(ApiResponseBatchUpdateParser.class.getName());

    public static boolean processResult(ApiResponse response, List<String> successList, List<String> failureList) {
        return processResult(response, successList, failureList, null);
    }

    public static boolean processResult(ApiResponse response, List<String> successList, List<String> failureList, Map<String, String> insertIdMap) {
        if (response.getData() == null || response.getData().isEmpty()) {
            logger.error("API批量更新响应数据为空, message={}", response.getMessage());
            return false;
        }

        JSONObject dataObject = (JSONObject) response.getData().get(0);

        if (successList != null) {
            JSONArray array = dataObject.getJSONArray(ApiConstant.API_RESPONSE_BATCH_SUCCESS);
            if (array != null && !array.isEmpty()) {
                for (Iterator<?> iter = array.iterator(); iter.hasNext();) {
                    String id = String.valueOf(iter.next());
                    successList.add(id);
                }
            }
        }

        if (failureList != null) {
            JSONArray array = dataObject.getJSONArray(ApiConstant.API_RESPONSE_BATCH_FAIL);
            if (array != null && !array.isEmpty()) {
                for (Iterator<?> iter = array.iterator(); iter.hasNext();) {
                    String id = String.valueOf(iter.next());
                    failureList.add(id);
                }
            }
        }

        if (insertIdMap != null) {
            JSONObject object = dataObject.getJSONObject(ApiConstant.API_RESPONSE_BATCH_INSERT_ID);
            if (object != null && !object.isEmpty()) {
                for (Iterator<?> iter = object.keySet().iterator(); iter.hasNext();) {
                    String key = String.valueOf(iter.next());
                    String val = object.getString(key);
                    insertIdMap.put(key, val);
                }
            }
        }

        return true;
    }
}
